package com.powergisol.gis.util;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileList {
    private static Logger logger = LoggerFactory.getLogger(FileList.class);

    public static Result fileRead(ZipFile zFile,String assinSuffixName,String unZipPath){
        Result result = new Result();
        List<File> list = new ArrayList<>();
        List<File> listSuffix = new ArrayList<>();
        //递归所有文件
        try {
            List<FileHeader> headerList = zFile.getFileHeaders();
            for(FileHeader fileHeader : headerList) {
                if (!fileHeader.isDirectory()) {
                    // 获取后缀
                    if (fileHeader.getFileName().indexOf(".") > -1) {
                        if(assinSuffixName.equalsIgnoreCase(fileHeader.getFileName().substring(fileHeader.getFileName().lastIndexOf(".") + 1))){
                            listSuffix.add(new File(unZipPath + fileHeader.getFileName()));
                        }
                    }
                    File file = new File(unZipPath + fileHeader.getFileName());
                    list.add(file);
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        }
        if(listSuffix.isEmpty()){
            logger.error("不存在"+assinSuffixName+"的文件");
            return result.failure(-3, "不存在"+assinSuffixName+"的文件");
        }
        String fileUrl = getFileUrl(listSuffix);
        Map<String,Object> map = new HashMap<>();
        map.put("listFile",list);
        map.put("fileUrl", fileUrl.replace("/",File.separator));
        return result.success(map);
    }

    /**
     * fileList
     * @param
     * @return
     */
    public static Result fileRead(String path,String assinSuffixName){

        Result result = new Result();
        //将此文件存入数据库
        File file = new File(path);
        if (!file.exists()) {
            return result.failure(-3, "文件不存在");
        }
        //递归同级文件及下级文件保存如数据数据库
        if(file.isFile()){
            path = path.substring(0, path.lastIndexOf(File.separator));
        }
        //List<File> list = recursionFile(path, null);
        logger.info("读取文件：{},{}",assinSuffixName,path);
        Map map = recursionFile(assinSuffixName,path,null,null);
        List<File> listSuffix = (List<File>)map.get("listSuffix");
        if(listSuffix.isEmpty()){
            logger.error("不存在"+assinSuffixName+"的文件");
            return result.failure(-3, "不存在"+assinSuffixName+"的文件");
        }
        String fileUrl = getFileUrl(listSuffix);
        map.remove("listSuffix");
        map.put("fileUrl", fileUrl.replace("/",File.separator));
        return result.success(map);
    }

    /**
     * fileList
     * @param
     * @return
     */
    public static Result fileReadSameName(String path){

        Result result = new Result();
        //将此文件存入数据库
        File file = new File(path);
        String name = file.getName();
        name = name.substring(0, name.indexOf("."));
        if (!file.exists()) {
            return result.failure(-3, "文件不存在");
        }
        //递归同级文件及下级文件保存如数据数据库
        if(file.isFile()){
            path = path.substring(0, path.lastIndexOf(File.separator));
        }
        List<File> list = new ArrayList<File> ();
        File fileList = new File(path);
        if(fileList.exists()){
            File[] files = fileList.listFiles();
            for (File file1:files){
                if(file1.isFile()){
                    if(file1.getName().contains(name)){
                        list.add(file1);
                    }
                }
            }
        }
        result.setData(list);
        return result;
    }

    private static String getFileUrl(List<File> list){

        String url = list.get(0).getAbsolutePath();
        int i= (url.length()-url.replace(File.separator,"").length())/File.separator.length();
        //int i=url.length()-url.replace(url, File.separator).length();
        for (File file:list) {
            int j =  (file.getAbsolutePath().length()-file.getAbsolutePath().replace(File.separator,"").length())/File.separator.length();
            if(i>j){
                url = file.getAbsolutePath();
                i=j;
            }else if(i == j){
                if(file.getAbsolutePath().contains("model.json")){
                    url = file.getAbsolutePath();
                    i=j;
                }
            }
        }
        return url;
    }

    /**
     * 读取目录下所有文件
     * @param recursionPath
     * @param list
     * @return
     * @throws IOException
     */
    public static List<File> recursionFile(String recursionPath,List<File> list) {
        if(null == list){
            list = new ArrayList<>();
        }
        File file = new File(recursionPath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        recursionFile(file1.getAbsolutePath(),list);
                    } else {
                        list.add(file1);
                    }
                }
            }
        }
        return list;
    }


    private static Map<String,Object> recursionFile(String assinSuffixName,String recursionPath,List<File> list,List<File> listSuffix) {
        if(null == list){
            list = new ArrayList<>();
        }
        if(null == listSuffix){
            listSuffix = new ArrayList<>();
        }
        Map<String,Object> map = new HashMap<>();
        File file = new File(recursionPath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        recursionFile(assinSuffixName,file1.getAbsolutePath(),list,listSuffix);
                    } else {
                        String fileName = file1.getName();
                        if(fileName.substring(fileName.lastIndexOf("."),fileName.length()).contains(assinSuffixName)){
                            listSuffix.add(file1);
                        }
                        list.add(file1);
                    }
                }
            }
        }
        map.put("listFile",list);
        map.put("listSuffix",listSuffix);
        return map;
    }



    public static Map<String,Object> recursionSelectFile(String assinSuffixName,String recursionPath,List<File> list,List<File> listSuffix) {
        if(null == list){
            list = new ArrayList<>();
        }
        if(null == listSuffix){
            listSuffix = new ArrayList<>();
        }
        Map<String,Object> map = new HashMap<>();
        String matchStr = "[-+0-9a-zA-Z_:.]{1,}";
        File file = new File(recursionPath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file1 : files) {
                    String filePath = file1.getPath().replace(File.separator,"");
                    if(!filePath.matches(matchStr)){
                        map.put("errorMsg", "文件命名应为数字、字母、横线、加号组成");
                        return map;
                    }
                    if (file1.isDirectory()) {
                        recursionSelectFile(assinSuffixName,file1.getAbsolutePath(),list,listSuffix);
                    } else {
                        String fileName = file1.getName();
                        if(fileName.substring(fileName.lastIndexOf("."),fileName.length()).contains(assinSuffixName)){
                            listSuffix.add(file1);
                        }
                        list.add(file1);
                    }
                }
            }
        }
        map.put("listFile",list);
        map.put("listSuffix",listSuffix);
        return map;
    }



    /**
     * 文件个数out
     *
     * @param fileArr
     */
    public static Integer getCountOut(File[] fileArr,Integer countOut) {
        //部分文件夹 无权限访问，返回null
        if (null == fileArr || fileArr.length <= 0) {
            return 0;
        }
        if(null == countOut){
            countOut = 0;
        }
        for (File file : fileArr) {
            if (file.isFile()) {
                countOut = countOut + 1;
            }
            if (file.isDirectory()) {
                System.out.println(countOut);
                countOut = getCountOut(file.listFiles(),countOut);
            }
        }
        return countOut;
    }

    public static void main(String[] args) {
        Map<String,Object> map = recursionSelectFile("","json",null,null);

        System.out.println(map.get("listFile"));
        System.out.println(map.get("listSuffix"));
    }

}
